import server from './index'
import notice from '../notice'
var fetch_config = {
  loading: true,
  loading_delay: 0,
  error: true,
  api_host: process.env.VUE_APP_REQUEST
};
export function set_fetch_config(obj) {
  fetch_config = {
    ...fetch_config,
    ...obj
  };
  return fetch_config
};

function handleResponse(res, config = {}) {
  var promise = new Promise(function (resolve, reject) {
    if (config.xhr) resolve(res);
    if (res.ok) {
      resolve(res.json());
    } else {
      notice.push_error('请求失败');
      reject(res);
    }
  }).then(data => {
    var errcode = Number(data.code);
    if (errcode === 200) {
      return data.data;
    } else {
      notice.push_error('请求失败：' + data.msg);
      return Promise.reject(data);
    }
  })
  return promise;
}

function http_request(method, url, params={}, config) {
  config = set_fetch_config(config);
  // params.token = window.sessionStorage.getItem('token');
  // console.log(JSON.stringify(params));
  url = (/http/.test(url) ? '' : config.api_host) + url;

  var loading_timer;
  if (config.loading) {
    if (config.loading_delay > 0) {
      loading_timer = setTimeout(function () {
        notice.show_loading();
      }, config.loading_delay);
    } else {
      notice.show_loading();
    }
  }
  return server[method](url, params, config)
    .then(function (res) {
      return handleResponse(res, url, config);
    })
    .finally(err => {
      if (config.loading) {
        clearTimeout(loading_timer);
        notice.hide_loading();
      }
    })
}

export function get(url, params = {}, config) {
  return http_request('get', url, params, config);
}

export function jsonp(url, params = {}, config) {
  return http_request('jsonp', url, params, config);
}

export function post(url, params = {}, config) {
  return http_request('post', url, params, config);
}

export function form(url, params = {}, config) {
  return http_request('form', url, params, config);
}

export function redirect(url, params = {}, config = {}) {
  config = set_fetch_config(config);
  if(process.env.NODE_ENV === 'production' && !/http/.test(url)){
    params.http = params.http || 1;
    params.toUrl = url;
    url = config.api_host;
  }
  var query = '';
  for (var k in params) {
    if (params[k]) {
      query += k + '=' + params[k] + '&';
    }
  }
  var link = url + '?' + query;
  window.location.href = link;
}

export default {
  get,
  post,
  form,
  redirect,
  jsonp
}
